<template>
	<view class="dxf-container" @click="dxf.onClick" :src="src" :change:src="dxf.updateSrc" :font-url="fontUrl"
		:change:font-url="dxf.updateFontUrl">
		<!-- #ifdef APP-PLUS || H5 -->
		<view id="dxf-view"></view>
		<!-- #endif -->
		<!-- #ifndef APP-PLUS || H5 -->
		<view>非 APP、H5 环境不支持</view>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		props: ['src', 'fontUrl'],
		emit: ['load'],
		methods: {
			onViewLoad() {
				this.$emit('load')
			}
		}
	}
</script>

<script module="dxf" lang="renderjs">
	export default {
		data() {
			return {
				srcR: '',
				fontUrlR: null
			}
		},
		mounted() {
			if (typeof window.threeDxfViewer === 'function') {
				this.initDxf()
			} else {
				const script1 = document.createElement('script')
				script1.src = 'static/dxf-parser.js'
				document.head.appendChild(script1)

				const script2 = document.createElement('script')
				script2.src = 'static/three-dxf-gai.es.js'
				script2.type = 'module'
				script2.onload = this.initDxf.bind(this)
				document.head.appendChild(script2)

				const viewEl = document.getElementById('dxf-view')
				const plusEl = document.getElementById('plus')
				const minusEl = document.getElementById('minus')

				const style = getComputedStyle(viewEl)
				this.width = Number.parseFloat(style.getPropertyValue('width')) || 100
				this.height = Number.parseFloat(style.getPropertyValue('height')) || 100
			}
		},
		methods: {
			async initDxf() {
				if (!this.srcR || !window.threeDxfViewer) return

				const content = await fetch(this.srcR).then(res => res.text())

				const viewEl = document.getElementById('dxf-view')
				const parser = new DxfParser()

				var dxf = parser.parseSync(content)
				viewEl.innerHTML = ''

				threeDxfViewer(dxf, viewEl, this.width, this.height, this.fontUrlR)
			},
			updateSrc(newValue, oldValue, ownerInstance, instance) {
				// 监听 service 层数据变更
				this.srcR = newValue
				this.initDxf.bind(this)().then(() => {
					ownerInstance.callMethod('onViewLoad')
				})
			},
			updateFontUrl(newValue, oldValue, ownerInstance, instance) {
				// 监听 service 层数据变更
				this.fontUrlR = newValue
				this.initDxf.bind(this)().then(() => {
					ownerInstance.callMethod('onViewLoad')
				})
			},
			onClick(event, ownerInstance) {
				// 调用 service 层的方法
				ownerInstance.callMethod('onViewClick', {
					test: 'test'
				})
			}
		}
	}
</script>

<style scoped>
	.dxf-container {
		width: 100%;
		height: 500px;
		position: relative;
		/* border: 1px solid rgba(0, 0, 0, 0.2); */
	}

	#dxf-view {
		width: 100%;
		height: 100%;
	}
</style>